import re

from rest_framework import serializers
from user.models import Users


# 验证邮箱
def check_email(value):
    if not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', value):
        raise serializers.ValidationError("邮箱格式不正确")
    else:
        emaildata = Users.objects.filter(email=value)
        if emaildata:
            raise serializers.ValidationError("邮箱已存在")


# 验证手机号
def check_phone(value):
    if not re.match(r'^1[3456789]\d{9}$', value):
        raise serializers.ValidationError("手机号格式不正确")
    else:
        phonedata = Users.objects.filter(phone=value)
        if phonedata:
            raise serializers.ValidationError("手机号已存在")


# 验证密码
def check_password(value):
    if not re.match(r'^[a-zA-Z0-9]{6,20}$', value):
        raise serializers.ValidationError("密码格式不正确")


# 验证用户名
def check_username(value):
    if not re.match(r'^[a-zA-Z0-9]{6,20}$', value):
        raise serializers.ValidationError("用户名格式不正确")


class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'
        extra_kwargs = {
            "email": {
                # "error_message": {
                #     "required": "邮箱不能为空",
                #     "unique": "邮箱已存在"
                # },
                "validators": [check_email]
            },
            "phone": {
                # "error_message": {
                #     "required": "手机号不能为空",
                #     "unique": "手机号已存在"
                # },
                "validators": [check_phone]
            },
            "password": {
                # "error_message": {
                #     "length": "密码长度为6-20位",
                #     "required": "密码不能为空",
                #     "unique": "密码已存在"},
                "validators": [check_password]
            },
            "usrername": {
                # "error_message": {
                #     "required": "用户名不能为空",
                #     "unique": "用户名已存在"},
                "validators": [check_username]
            }
        }
